<template>
  <l-layout class="l-tab-page" :left="544" v-loading="moduleLoading">
    <template #left>
      <l-panel style="padding-right: 0px">
        <div class="l-auto-window" style="padding: 0 8px">
          <el-tabs v-model="tabsActiveName" :before-leave="handleRoleToUser">
            <el-tab-pane :label="$t('角色')" name="tabRole">
              <l-layout :bottom="40">
                <div class="l-rblock" style="padding-top: 8px">
                  <l-table
                    @rowClick="handleRowClick"
                    :highlightCurrentRow="true"
                    :columns="roleColumns"
                    :dataSource="searchRoleData"
                  >
                  </l-table>
                </div>
                <template #bottom>
                  <el-input
                    :placeholder="$t('请输入编号/名称')"
                    @keyup.enter.native="hanleSearchRole"
                    v-model="searchRoleWord"
                    size="mini"
                  >
                    <el-button @click="hanleSearchRole" slot="append" icon="el-icon-search"></el-button>
                  </el-input>
                </template>
              </l-layout>
            </el-tab-pane>
            <el-tab-pane :label="$t('人员')" name="tabUser">
              <l-layout :bottom="40">
                <div class="l-rblock" style="padding-top: 8px">
                  <l-table
                    @rowClick="handleRowClick"
                    :highlightCurrentRow="true"
                    :columns="userColumns"
                    :dataSource="userData"
                    row-key="f_UserId"
                    :isPage="true"
                    :pageTotal="userTotal"
                    :tablePage.sync="userCurrentPage"
                    @loadPageData="turnUserPage"
                  >
                    <template v-slot:f_CompanyId="scope">
                      {{ (lr_companyList.find((t) => t.f_CompanyId == scope.row.f_CompanyId) || {}).f_FullName || "" }}
                    </template>
                    <template v-slot:f_DepartmentId="scope">
                      {{ lr_departmentName(lr_departments[scope.row.f_CompanyId] || [], scope.row.f_DepartmentId) }}
                    </template>
                  </l-table>
                </div>
                <template #bottom>
                  <el-input
                    :placeholder="$t('请输入帐号/名称')"
                    @keyup.enter.native="hanleSearchUser"
                    v-model="searchUserWord"
                    size="mini"
                  >
                    <el-button @click="hanleSearchUser" slot="append" icon="el-icon-search"></el-button>
                  </el-input>
                </template>
              </l-layout>
            </el-tab-pane>
          </el-tabs>
        </div>
      </l-panel>
    </template>
    <l-panel :title="`${type}${name ? '-' : ''}${name}`" style="padding-left: 0px">
      <div class="l-auto-window" style="padding: 0 8px">
        <el-tabs v-model="tabsActiveName2" :before-leave="handleTabLeave">
          <el-tab-pane :label="$t('功能')" name="tabModule">
            <div v-if="!isSelectOne" class="empty-text">{{ emptyText }}</div>
            <l-layout v-else :bottom="40">
              <div class="l-rblock" style="overflow: auto">
                <el-tree
                  ref="appTree"
                  :data="appTree"
                  show-checkbox
                  default-expand-all
                  node-key="f_Id"
                  @check="handleAppCheck"
                >
                  <span class="lr-tree-node" slot-scope="{ data }">
                    {{ $t(data.label) }}
                  </span>
                </el-tree>
              </div>
              <template #bottom>
                <div class="l-rblock" style="text-align: right">
                  <el-button @click="handleAppCancel" :disabled="!isSaveApp" size="mini">取消</el-button>
                  <el-button @click="handleAppSave" :disabled="!isSaveApp" size="mini" type="primary">保存</el-button>
                </div>
              </template>
            </l-layout>
          </el-tab-pane>

          <el-tab-pane :label="$t('按钮')" name="tabButton">
            <div v-if="!isSelectOne" class="empty-text">{{ emptyText }}</div>
            <l-layout v-else :left="240" :bottom="40">
              <div class="l-rblock" style="overflow: auto">
                <el-tree
                  ref="buttonTree"
                  :data="buttonTree"
                  show-checkbox
                  default-expand-all
                  node-key="f_Code"
                  @check="handleButtonCheck"
                >
                  <span class="lr-tree-node" slot-scope="{ data }">
                    {{ $t(data.label) }}
                  </span>
                </el-tree>
              </div>
              <template #left>
                <div class="l-rblock" style="overflow: auto; border-right: 1px solid #e4e7ed">
                  <el-tree :data="myAppTree" default-expand-all node-key="f_Id" @node-click="handleModuleClick">
                    <span class="lr-tree-node" slot-scope="{ data }">
                      {{ $t(data.label) }}
                    </span>
                  </el-tree>
                </div>
              </template>
              <template #bottom>
                <div class="l-rblock" style="text-align: right">
                  <el-button @click="handleButtonCancel" :disabled="!isSaveButton" size="mini">取消</el-button>
                  <el-button @click="handleButtonSave" :disabled="!isSaveButton" size="mini" type="primary"
                    >保存</el-button
                  >
                </div>
              </template>
            </l-layout>
          </el-tab-pane>

          <el-tab-pane :label="$t('列表')" name="tabCol">
            <div v-if="!isSelectOne" class="empty-text">{{ emptyText }}</div>
            <l-layout v-else :left="240" :bottom="40">
              <div class="l-rblock" style="overflow: auto">
                <el-tree
                  ref="columnTree"
                  :data="columnTree"
                  show-checkbox
                  default-expand-all
                  node-key="f_Code"
                  @check="handleColumnCheck"
                >
                  <span class="lr-tree-node" slot-scope="{ data }">
                    {{ $t(data.label) }}
                  </span>
                </el-tree>
              </div>
              <template #left>
                <div class="l-rblock" style="overflow: auto; border-right: 1px solid #e4e7ed">
                  <el-tree :data="myAppTree" default-expand-all node-key="f_Id" @node-click="handleColModuleClick">
                    <span class="lr-tree-node" slot-scope="{ data }">
                      {{ $t(data.label) }}
                    </span>
                  </el-tree>
                </div>
              </template>
              <template #bottom>
                <div class="l-rblock" style="text-align: right">
                  <el-button @click="handleColumnCancel" :disabled="!isSaveColumn" size="mini">取消</el-button>
                  <el-button @click="handleColumnSave" :disabled="!isSaveColumn" size="mini" type="primary"
                    >保存</el-button
                  >
                </div>
              </template>
            </l-layout>
          </el-tab-pane>

          <el-tab-pane :label="$t('表单')" name="tabForm">
            <div v-if="!isSelectOne" class="empty-text">{{ emptyText }}</div>
            <l-layout v-else :left="240" :bottom="40">
              <div class="l-rblock" style="overflow: auto">
                <l-table :columns="formColumns" :dataSource="formTableData">
                  <template v-slot:isEdit="scope">
                    <el-switch
                      v-if="!scope.row.noEdit"
                      v-model="scope.row.isEdit"
                      :active-value="1"
                      :inactive-value="0"
                      @change="handleFormCheck(scope.row, false)"
                    >
                    </el-switch>
                  </template>
                  <template v-slot:isLook="scope">
                    <el-switch
                      v-model="scope.row.isLook"
                      :active-value="1"
                      :inactive-value="0"
                      @change="handleFormCheck(scope.row, true)"
                    >
                    </el-switch>
                  </template>
                </l-table>
              </div>
              <template #left>
                <div class="l-rblock" style="overflow: auto; border-right: 1px solid #e4e7ed">
                  <el-tree :data="myAppTree" default-expand-all node-key="f_Id" @node-click="handleFormModuleClick">
                    <span class="lr-tree-node" slot-scope="{ data }">
                      {{ $t(data.label) }}
                    </span>
                  </el-tree>
                </div>
              </template>
              <template #bottom>
                <div class="l-rblock" style="text-align: right">
                  <el-button @click="handleFormCancel" :disabled="!isSaveForm" size="mini">取消</el-button>
                  <el-button @click="handleFormSave" :disabled="!isSaveForm" size="mini" type="primary">保存</el-button>
                </div>
              </template>
            </l-layout>
          </el-tab-pane>
        </el-tabs>
      </div>
    </l-panel>
  </l-layout>
</template>

<script>
const api = window.$api.permission.module;
const apiRole = window.$api.organization.role;
const apiUser = window.$api.organization.user;
const apiModule = window.$api.mapp.module;

const apiAppFunction = window.$api.mapp.module;

export default {
  data() {
    return {
      lr_isPage: true,
      lr_isAuth: false,

      tabsActiveName: "tabRole",
      tabsActiveName2: "tabModule",

      name: "",
      id: "",

      searchRoleWord: "",
      searchRoleData: [],
      roleData: [],
      roleColumns: [
        { label: "编号", prop: "f_EnCode", minWidth: "110" },
        { label: "名称", prop: "f_FullName", minWidth: "120" },
      ],

      searchUserWord: "",
      userData: [],
      userColumns: [
        { label: "姓名", prop: "f_RealName", width: "88" },
        { label: "账号", prop: "f_Account", width: "88" },
        { label: "公司", prop: "f_CompanyId", minWidth: "100" },
        { label: "部门", prop: "f_DepartmentId", minWidth: "100" },
      ],
      userTotal: 0,
      userPageSize: 50,
      userCurrentPage: 1,

      // 是否选中人员
      isSelectOne: false,

      // 功能
      moduleLoading: false,
      // app
      apps: [],
      myapps: [],
      appOldChecked: [],
      appChecked: [],
      moduleId: "",

      // 按钮
      buttons: [],
      mybuttons: [],
      buttonList: [],
      buttonChecked: [],

      // 列表
      columns: [],
      mycolumns: [],
      columnList: [],
      columnChecked: [],

      // 表
      forms: [],
      myforms: [],
      formList: [],
      formChecked: [],
      formColumns: [
        { label: "名称", prop: "f_Name", minWidth: "100" },
        { label: "编辑", prop: "isEdit", width: "64", align: "center" },
        { label: "查看", prop: "isLook", width: "64", align: "center" },
      ],
      formTableData: [],
    };
  },
  async mounted() {
    this.moduleLoading = true;
    await Promise.all([this.loadRoleData(), this.lr_loadCompanys(), this.loadUserData(), this.loadAppList()]);
    this.moduleLoading = false;
  },
  computed: {
    type() {
      return this.tabsActiveName == "tabRole" ? "角色" : "人员";
    },
    emptyText() {
      return this.tabsActiveName == "tabRole" ? "请选择一个角色查看" : "请选择一个人员查看";
    },

    // 按钮
    buttonTree() {
      let list = this.buttons;
      if (this.loginInfo.f_SecurityLevel != 1) {
        list = this.buttons.filter((t) => this.mybuttons.indexOf(t.f_Code) != -1);
      }
      //console.log(list,'list')

      const res = this.$toTree(list, "f_Id", "f_ParentId", "f_Code", "f_Name");
      return res;
    },
    isSaveButton() {
      return !this.equalsArr(this.buttonList, this.buttonChecked);
    },

    // 列表
    columnTree() {
      let list = this.columns;
      if (this.loginInfo.f_SecurityLevel != 1) {
        list = this.columns.filter((t) => this.mycolumns.indexOf(t.f_Code) != -1);
      }

      const res = this.$toTree(list, "f_Id", "f_ParentId", "f_Code", "f_Name");
      return res;
    },
    isSaveColumn() {
      return !this.equalsArr(this.columnList, this.columnChecked);
    },
    isSaveForm() {
      return !this.equalsArr(this.formList, this.formChecked);
    },

    // app功能
    isSaveApp() {
      return !this.equalsArr(this.appOldChecked, this.appChecked);
    },
    appList() {
      let list = this.apps;
      if (this.loginInfo.f_SecurityLevel != 1) {
        list = this.apps.filter((t) => this.myapps.indexOf(t.f_Id) != -1);
      }
      return list;
    },
    appTree() {
      return this.getAppTree(this.appList);
    },
    myAppTree() {
      const list = this.appList.filter(
        (t) => t.f_IsSystem != 3 && t.f_IsSystem != 4 && this.appChecked.indexOf(t.f_Id) > -1
      );
      return this.getAppTree(list);
    },
  },
  methods: {
    equalsArr(arr1, arr2) {
      let flag = true;
      if (arr1.length !== arr2.length) {
        flag = false;
      } else {
        arr1.forEach((item) => {
          if (arr2.indexOf(item) === -1) {
            flag = false;
          }
        });
      }
      return flag;
    },
    // 获取移动功能树形数据
    getAppTree(list) {
      const map = {};
      const res = [];
      const dataItemList = this.lr_dataItem["function"];
      dataItemList.forEach((item) => {
        let point = {
          label: item.f_ItemName,
          value: item.f_ItemValue,
          children: [],
        };
        map[item.f_ItemValue] = point.children;
        res.push(point);
      });
      list.forEach((item) => {
        item.label = item.f_Name;
        item.value = item.f_Id;
        if (!map[item.f_Type]) {
          // 解决部分功能分类数据被删除
          let point = {
            label: item.f_Type,
            value: item.f_Type,
            children: [],
          };
          map[item.f_Type] = point.children;
          res.push(point);
        }
        map[item.f_Type].push(item);
      });
      return res.filter((t) => t.children.length > 0);
    },

    // 角色人员切换
    async handleRoleToUser() {
      await this.leave();
      this.name = "";
      this.id = "";
      this.isSelectOne = false;
    },

    // 角色
    hanleSearchRole() {
      if (this.searchRoleWord) {
        this.searchRoleData = this.roleData.filter(
          (item) => item.f_FullName.indexOf(this.searchRoleWord) > -1 || item.f_EnCode.indexOf(this.searchRoleWord) > -1
        );
      } else {
        this.searchRoleData = this.roleData;
      }
    },
    loadRoleData() {
      apiRole.getList().then((res) => {
        this.searchRoleWord = "";
        this.roleData = res.data.data.filter((t) => t.f_EnabledMark == 1);
        this.searchRoleData = this.roleData;
      });
    },

    // 人员
    loadUserData(isNotFirst) {
      if (!isNotFirst) {
        this.userCurrentPage = 1;
      }
      let queryData = {
        rows: this.userPageSize,
        page: this.userCurrentPage,
        sidx: "F_CreateDate DESC",
        keyword: this.searchUserWord,
      };
      apiUser
        .getPage(queryData)
        .then((res) => {
          const data = this.$deepClone(res.data.data);
          data.rows.forEach((item) => {
            this.lr_loadDepartments(item.f_CompanyId);
          });
          this.userData = data.rows;
          this.userTotal = data.records;
        })
        .catch(() => {
          this.userData = [];
        });
    },
    turnUserPage({ rows }) {
      this.tablePageSize = rows;
      this.loadUserData(true);
    },
    hanleSearchUser() {
      this.loadUserData();
    },

    async handleRowClick(row) {
      await this.leave();
      if (this.tabsActiveName == "tabRole") {
        this.name = row.f_FullName;
        this.id = row.f_RoleId;
      } else {
        this.name = row.f_RealName;
        this.id = row.f_UserId;
      }
      this.isSelectOne = true;

      this.moduleChecked = [];
      this.moduleList = [];
      this.loadApps();

      //console.log("test");
    },

    async leave() {
      switch (this.tabsActiveName2) {
        case "tabModule":
          await this.leaveModule();
          break;
        case "tabButton":
          await this.leaveButton();
          break;
        case "tabCol":
          await this.leaveColumn();
          break;
        case "tabForm":
          await this.leaveForm();
          break;
      }
    },

    async handleTabLeave() {
      switch (this.tabsActiveName2) {
        case "tabModule":
          await this.leaveModule2();
          break;
        case "tabButton":
          await this.leaveButton();
          break;
        case "tabCol":
          await this.leaveColumn();
          break;
        case "tabForm":
          await this.leaveForm();
          break;
        case "tabApp":
          await this.leaveApp2();
          break;
      }
    },

    // 功能模块
    async loadAppList() {
      await this.lr_loadDataItem("function");
      this.apps = await this.$awaitWraper(apiAppFunction.getList());
    },
    async loadApps() {
      const res = await this.$awaitWraper(api.getList(this.id, 5, "0"));
      this.myapps = res.myList || [];
      this.appOldChecked = res.settingList.map((t) => t.f_ItemId);
      this.appChecked = this.$deepClone(this.appOldChecked);
      this.$refs.appTree.setCheckedKeys(this.appOldChecked);
    },

    handleAppCheck(node, data) {
      this.appChecked = data.checkedKeys.concat(data.halfCheckedKeys).filter((t) => t != undefined);
    },

    handleAppCancel() {
      this.appChecked = this.$deepClone(this.appOldChecked);
      this.$refs.formTree.setCheckedKeys(this.appChecked);
    },
    async handleAppSave() {
      this.moduleLoading = true;
      const data = {
        ids: this.appChecked,
        objectType: this.tabsActiveName == "tabRole" ? 1 : 2,
        itemType: 5,
        parentId: "0",
      };
      const res = await this.$awaitWraper(api.save(this.id, data));
      if (res) {
        this.$message({
          type: "success",
          message: "保存成功!",
        });
        this.appOldChecked = this.$deepClone(this.appChecked);
      }
      this.moduleLoading = false;
    },

    leaveModule() {
      return new Promise((resolve) => {
        if (this.isSaveApp) {
          this.$confirm(this.$t("离开前,是否保存设置数据?"), this.$t("提示"), {
            confirmButtonText: this.$t("确定"),
            cancelButtonText: this.$t("取消"),
            type: "warning",
          })
            .then(async () => {
              await this.handleAppSave();
              this.appOldChecked = [];
              this.appChecked = [];
              this.myapps = [];
              resolve();
            })
            .catch(() => {
              this.appOldChecked = [];
              this.appChecked = [];
              this.myapps = [];
              resolve();
            });
        } else {
          this.appOldChecked = [];
          this.appChecked = [];
          this.myapps = [];
          resolve();
        }
      });
    },
    leaveModule2() {
      return new Promise((resolve) => {
        if (this.isSaveApp) {
          this.$confirm(this.$t("离开前,是否保存设置数据?"), this.$t("提示"), {
            confirmButtonText: this.$t("确定"),
            cancelButtonText: this.$t("取消"),
            type: "warning",
          }).then(async () => {
            await this.handleAppSave();
            resolve();
          });
        } else {
          resolve();
        }
      });
    },

    // 按钮
    async handleModuleClick(data) {
      if (this.moduleId == data.value) {
        return;
      }
      await this.leaveButton();
      this.moduleId = data.value;
      if (data.children) {
        this.buttons = [];
        this.mybuttons = [];
        this.buttonList = [];
        this.buttonChecked = [];
      } else {
        this.moduleLoading = true;
        const point = {
          f_Id: "0",
          f_ParentId: "01",
          f_Code: "0",
          f_Name: data.f_Name,
        };
        const res = await this.$awaitWraper(apiModule.getChildren(data.value, 1));
        res.forEach((t) => (t.f_ParentId = "0"));
        res.push(point);
        await this.loadButtons(data.value);
        this.buttons = res;

        this.$refs.buttonTree.setCheckedKeys(this.buttonList);

        this.moduleLoading = false;
      }
    },
    async loadButtons(moduleId) {
      const res = await this.$awaitWraper(api.getList(this.id, 6, moduleId));
      this.mybuttons = res.myList || [];
      this.buttonList = res.settingList.map((t) => t.f_ItemId);
      this.buttonChecked = this.$deepClone(this.buttonList);
    },
    handleButtonCheck(node, data) {
      this.buttonChecked = data.checkedKeys.concat(data.halfCheckedKeys).filter((t) => t != "0");
    },
    handleButtonCancel() {
      this.buttonChecked = this.$deepClone(this.buttonList);
      this.$refs.buttonTree.setCheckedKeys(this.buttonChecked);
    },
    async handleButtonSave() {
      this.moduleLoading = true;
      const data = {
        ids: this.buttonChecked,
        objectType: this.tabsActiveName == "tabRole" ? 1 : 2,
        itemType: 6,
        parentId: this.moduleId,
      };
      const res = await this.$awaitWraper(api.save(this.id, data));
      if (res) {
        this.$message({
          type: "success",
          message: "保存成功!",
        });
        this.buttonList = this.$deepClone(this.buttonChecked);
      }

      this.moduleLoading = false;
    },
    leaveButton() {
      return new Promise((resolve) => {
        if (this.isSaveButton) {
          this.$confirm(this.$t("离开前,是否保存设置数据?"), this.$t("提示"), {
            confirmButtonText: this.$t("确定"),
            cancelButtonText: this.$t("取消"),
            type: "warning",
          })
            .then(async () => {
              await this.handleButtonSave();
              this.buttonList = [];
              this.buttonChecked = [];
              this.mybuttons = [];
              this.buttons = [];
              this.moduleId = "";
              resolve();
            })
            .catch(() => {
              this.buttonList = [];
              this.buttonChecked = [];
              this.mybuttons = [];
              this.buttons = [];
              this.moduleId = "";
              resolve();
            });
        } else {
          this.buttonList = [];
          this.buttonChecked = [];
          this.mybuttons = [];
          this.buttons = [];
          this.moduleId = "";
          resolve();
        }
      });
    },

    // 列表
    async handleColModuleClick(data) {
      if (this.moduleId == data.value) {
        return;
      }
      await this.leaveColumn();
      this.moduleId = data.value;
      if (data.children) {
        this.columns = [];
        this.mycolumns = [];
        this.columnList = [];
        this.columnChecked = [];
      } else {
        this.moduleLoading = true;
        const point = {
          f_Id: "0",
          f_ParentId: "01",
          f_Code: "0",
          f_Name: data.f_Name,
        };
        const res = await this.$awaitWraper(apiModule.getChildren(data.value, 2));
        res.forEach((t) => (t.f_ParentId = "0"));
        res.push(point);
        await this.loadColumns(data.value);
        this.columns = res;

        this.$refs.columnTree.setCheckedKeys(this.columnList);
        this.moduleLoading = false;
      }
    },
    async loadColumns(moduleId) {
      const res = await this.$awaitWraper(api.getList(this.id, 7, moduleId));
      this.mycolumns = res.myList || [];
      this.columnList = res.settingList.map((t) => t.f_ItemId);
      this.columnChecked = this.$deepClone(this.columnList);
    },
    handleColumnCheck(node, data) {
      this.columnChecked = data.checkedKeys.concat(data.halfCheckedKeys).filter((t) => t != "0");
    },
    handleColumnCancel() {
      this.columnChecked = this.$deepClone(this.columnList);
      this.$refs.columnTree.setCheckedKeys(this.columnChecked);
    },
    async handleColumnSave() {
      this.moduleLoading = true;
      const data = {
        ids: this.columnChecked,
        objectType: this.tabsActiveName == "tabRole" ? 1 : 2,
        itemType: 7,
        parentId: this.moduleId,
      };
      const res = await this.$awaitWraper(api.save(this.id, data));
      if (res) {
        this.$message({
          type: "success",
          message: "保存成功!",
        });
        this.columnList = this.$deepClone(this.columnChecked);
      }

      this.moduleLoading = false;
    },
    leaveColumn() {
      return new Promise((resolve) => {
        if (this.isSaveColumn) {
          this.$confirm(this.$t("离开前,是否保存设置数据?"), this.$t("提示"), {
            confirmButtonText: this.$t("确定"),
            cancelButtonText: this.$t("取消"),
            type: "warning",
          })
            .then(async () => {
              await this.handleColumnSave();
              this.columnList = [];
              this.columnChecked = [];
              this.mycolumns = [];
              this.columns = [];
              this.moduleId = "";
              resolve();
            })
            .catch(() => {
              this.columnList = [];
              this.columnChecked = [];
              this.mycolumns = [];
              this.columns = [];
              this.moduleId = "";
              resolve();
            });
        } else {
          this.columnList = [];
          this.columnChecked = [];
          this.mycolumns = [];
          this.columns = [];
          this.moduleId = "";
          resolve();
        }
      });
    },

    // 表单
    async handleFormModuleClick(data) {
      if (this.moduleId == data.value) {
        return;
      }
      await this.leaveForm();
      this.moduleId = data.value;
      if (data.f_Target == "expand") {
        this.forms = [];
        this.myforms = [];
        this.formList = [];
        this.formChecked = [];
      } else {
        this.moduleLoading = true;
        const res = await this.$awaitWraper(apiModule.getChildren(data.value, 3));
        await this.loadForms(data.value);
        this.forms = res;
        this.setFormTableData();

        this.moduleLoading = false;
      }
    },
    async loadForms(moduleId) {
      const res = await this.$awaitWraper(api.getList(this.id, 8, moduleId));
      this.myforms = res.myList || [];
      this.formList = res.settingList.map((t) => `${t.f_ItemId},${t.f_Type || 2}`);
      this.formChecked = this.$deepClone(this.formList);
    },
    setFormTableData() {
      const list = [];
      if (this.loginInfo.f_SecurityLevel != 1) {
        const myformMap = {};
        this.myforms.forEach((item) => {
          const itemList = item.split(",");
          myformMap[itemList[0].toLowerCase()] = itemList[1];
        });

        this.forms.forEach((item) => {
          if (myformMap[item.f_Code.toLowerCase()]) {
            if (myformMap[item.f_Code.toLowerCase()] == 1) {
              list.push({ f_Name: item.f_Name, f_Code: item.f_Code, noEdit: true, isEdit: 0, isLook: 0 });
            } else {
              list.push({ f_Name: item.f_Name, f_Code: item.f_Code, isEdit: 0, isLook: 0 });
            }
          }
        });
      } else {
        this.forms.forEach((item) => {
          list.push({ f_Name: item.f_Name, f_Code: item.f_Code, isEdit: 0, isLook: 0 });
        });
      }

      const checkformMap = {};
      this.formList.forEach((item) => {
        const itemList = item.split(",");
        checkformMap[itemList[0].toLowerCase()] = itemList[1];
      });

      list.forEach((item) => {
        if (checkformMap[item.f_Code.toLowerCase()]) {
          item.isLook = 1;
          if (checkformMap[item.f_Code.toLowerCase()] != 1) {
            item.isEdit = 1;
          }
        }
      });

      this.formTableData = list;
    },

    handleFormCheck(row, isLook) {
      const checkRowIndex = this.formChecked.findIndex(
        (t) => t.split(",")[0].toLowerCase() == row.f_Code.toLowerCase()
      );
      let type = 0;
      if (row.isLook == 1) {
        type = 1;
      } else if (isLook) {
        row.isEdit = 0;
      }

      if (row.isEdit == 1) {
        type = 2;
        if (!isLook) {
          row.isLook = 1;
        }
      }

      if (checkRowIndex == -1 && type != 0) {
        this.formChecked.push(`${row.f_Code},${type}`);
      } else {
        this.formChecked.splice(checkRowIndex, 1);
        if (type != 0) {
          this.formChecked.push(`${row.f_Code},${type}`);
        }
      }
    },
    handleFormCancel() {
      this.formChecked = this.$deepClone(this.formList);
      this.setFormTableData();
    },
    async handleFormSave() {
      this.moduleLoading = true;
      const data = {
        ids: this.formChecked,
        objectType: this.tabsActiveName == "tabRole" ? 1 : 2,
        itemType: 8,
        parentId: this.moduleId,
      };
      const res = await this.$awaitWraper(api.save(this.id, data));
      if (res) {
        this.$message({
          type: "success",
          message: "保存成功!",
        });
        this.formList = this.$deepClone(this.formChecked);
      }

      this.moduleLoading = false;
    },
    leaveForm() {
      return new Promise((resolve) => {
        if (this.isSaveForm) {
          this.$confirm(this.$t("离开前,是否保存设置数据?"), this.$t("提示"), {
            confirmButtonText: this.$t("确定"),
            cancelButtonText: this.$t("取消"),
            type: "warning",
          })
            .then(async () => {
              await this.handleFormSave();
              this.formList = [];
              this.formChecked = [];
              this.myforms = [];
              this.forms = [];
              this.formTableData = [];
              this.moduleId = "";
              resolve();
            })
            .catch(() => {
              this.formList = [];
              this.formChecked = [];
              this.myforms = [];
              this.forms = [];
              this.formTableData = [];
              this.moduleId = "";
              resolve();
            });
        } else {
          this.formList = [];
          this.formChecked = [];
          this.myforms = [];
          this.forms = [];
          this.formTableData = [];
          this.moduleId = "";
          resolve();
        }
      });
    },
  },
};
</script>
<style lang="scss" scoped>
.empty-text {
  width: 100%;
  text-align: center;
  margin-top: -30px;
  box-sizing: border-box;
  top: 50%;
  position: absolute;
  left: 0;
  line-height: 60px;
  font-size: 14px;
  color: #909399;
}
</style>
